{ "cells": [ { "metadata": {}, "cell_type": "markdown", "source": [ "# Class Notes 30/09/2025 — While loops, For loops & Iterables\n", "## Try me\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ffraile/computer_science_tutorials/blob/main/source/Introduction/class%20notes/class_notes_30092025.ipynb)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ffraile/computer_science_tutorials/main?labpath=source%2FIntroduction%2Fclass%20notes%2Fclass_notes_30092025.ipynb)\n", "\n", "## 2) `while` Loops\n", "\n", "**Definition:** Repeat a block **while** a condition remains `True`.\n", "**Syntax:**\n", "```python\n", "while condition:\n", " # loop body\n", " # executed while the condition is True\n", " # condition is re-evaluated each iteration\n", "```\n", "**Important**\n", "- Ensure the loop **eventually stops** (update variables, read input, etc.).\n", "- Use `break` to exit early; `continue` to skip to next iteration.\n", "\n", "\n" ], "id": "ccba7f23a93fb21" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "# Example: echo until user types 'quit' (safe sentinel pattern)\n", "while True:\n", " msg = input(\"Say something ('quit' to stop): \")\n", " if msg.strip().lower() == \"quit\":\n", " break # exit the loop\n", " if not msg: # empty input? skip\n", " continue\n", " print(\"You said:\", msg)\n", "print(\"Bye!\")" ], "id": "b51ef080f01bfa73" }, { "metadata": {}, "cell_type": "markdown", "source": [ "**`break` / `continue` demo**\n", "\n", "\n" ], "id": "32a0e8c62164ac10" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "x = 0\n", "y = 0\n", "while x < 5:\n", " x += 1\n", " if x % 2 == 0: # even\n", " print(x, \"is even\")\n", " continue # go to next iteration (skip y += x)\n", " y += x # odd: accumulate\n", "print(\"Sum of odd numbers 1..5 is\", y)" ], "id": "68d11efaa0fe47ee" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": "", "id": "1e020adca574dc8d" }, { "metadata": {}, "cell_type": "markdown", "source": [ "## 3) Iterables: Lists\n", "\n", "**Definition:** Ordered, indexable, mutable collection.\n", "**Create:** `lst = [a, b, c]` • Empty: `[]` • Length: `len(lst)`\n", "**Indexing:** `lst[i]` (0-based) • Negative index from end: `lst[-1]`\n", "\n", "**Common ops:** `append`, `pop`, `insert`, `remove`, `in`, `count`\n", "\n", "\n" ], "id": "16b89b7b5028a73" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "row = [\"A\", \"B\", \"C\"]\n", "print(len(row), row[0], row[-1]) # 3 A C\n", "row.append(\"D\")\n", "print(row) # [\"A\", \"B\", \"C\", D]" ], "id": "195f48218f5fad0b" }, { "metadata": {}, "cell_type": "markdown", "source": [ "### 3.1 Slicing\n", "\n", "- **Syntax:** `seq[start:stop:step]` slices seq from start to stop with step (stop **excluded**)\n", "- Omitted parts default to start, step 1, or end of the sequence.\n", "- Use negative step to go backwards\n" ], "id": "e78199184ad5c23c" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "s = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]\n", "print(s[1:4]) # ['B','C','D']\n", "print(s[:3]) # first three\n", "print(s[3:]) # from index 3 to end\n", "print(s[::2]) # every 2nd\n", "print(s[::-1]) # reversed copy" ], "id": "2870cd62bb7e3d25" }, { "metadata": {}, "cell_type": "markdown", "source": [ "## 4) `for` Loops\n", "\n", "**Definition:** Iterate over the elements of an iterable.\n", "**Syntax:**\n", "```python\n", "for element in iterable:\n", " # use element\n", "```\n", "**Tips**\n", "- Use `for name in names:` to get items; use `enumerate(iterable)` when you also need the index.\n", "- `continue` and `break` work as in `while` loops.\n", "\n", "### Grasping the concept: Iteration\n", "#### Real‑world example: corporate emails\n", "Let us write a hand-made email generator. Each student in the first row, given their full name, should write in the whiteboard an email with the following format:\n", "**Rule:** first initial + surname (lowercase, no spaces/hyphens) + `@stark_company.com`" ], "id": "9b04af7f2e28bc2f" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "\n", "names = [\"Tony Stark\", \"Bruce Banner\", \"Thor Odinson\"]\n", "for full in names:\n", " print(full) #prints names in different lines\n", "\n", "for i, full in enumerate(names, start=1):\n", " print(i, full)" ], "id": "30f2589460c7410c" }, { "metadata": {}, "cell_type": "markdown", "source": [ "### 4.1 Range\n", "The ```range``` function is a built-in function widely used in combination with for loops.\n", "- Use `range(n)` to loop a specific number of times.\n", "- Use `range(start,stop,step) as in slicing to generate a specific numeric sequence\n", "\n", "for i in range(5):\n" ], "id": "1edca04050eb7e8" }, { "metadata": {}, "cell_type": "code", "outputs": [], "execution_count": null, "source": [ "for i in range(5):\n", " print(i) # prints 0, 1, 2, 3, 4\n", "\n", "for i in range(1,7,2):\n", " print(i) # prints (1, 3, 5)" ], "id": "dc4f2b891c8e4e04" }, { "metadata": {}, "cell_type": "markdown", "source": [ "## 5) Quick Checks (self‑test)\n", "\n", "1) What does this print and **why**?\n", "```python\n", "x = 20\n", "if x < 20:\n", " msg = \"A\"\n", "elif x <= 20:\n", " msg = \"B\"\n", "else:\n", " msg = \"C\"\n", "print(msg)\n", "```\n", "2) Write a loop that sums only the **even** numbers in `nums = [0,1,2,3,4,5]`.\n", "3) Slice `letters = list(\"ABCDEFG\")` to get `[\"C\",\"D\",\"E\"]`.\n", "4) Turn the rule “`age` between 18 and 64 inclusive” into a single boolean expression.\n", "5) Try writing the corporate email generator from the example above.\n", "\n", "\n" ], "id": "6f6989862a80b5ce" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 5 }